<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Remote Preview</title>
    <meta name="apple-mobile-web-app-title" content="Remote">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">
    <style>
      * {
        margin: 0;
        padding: 0;
        border: 0;
      }
      html, body {
        height: 100%;
      }
      body {
        position: relative;
      }
      iframe {
        position: absolute;
        height: 101.5%; /* Fixes the bottom margin on IE9 Mobile */
        width: 100%;
        left: 0;
        top: 0;
      }
    </style>
    <script src="jquery.js"></script>
    <script>
      /*global $ */

      /**
       * Check if it's an URL.
       * @return boolean
       */
      function isUrl(url) {
        var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
        return regexp.test(url);
      }

      function isAndroidEmulator() {
        return window.location.href.match('10.0.2.2');
      }

      function sanitizeUrl(url) {
        var sanitizedUrl;
        if(isAndroidEmulator() && url.match(/localhost/i)) {
            sanitizedUrl = url.split('localhost').join('10.0.2.2');
        } else {
          sanitizedUrl = url;
        }
        return sanitizedUrl;
      }

      // Poll URLs.
      function remotePreview() {
        $.ajax({
          url: 'url.txt',
          cache: false,
          timeout: 100000,
          dataType: 'text',

          success: function (data) {
            // Remove whitespace from the beginning and end
            var newUrl = $.trim(data);

            // Check URL against regexp and stop if false
            if (!isUrl(newUrl)) {
              setTimeout(remotePreview, 1100);
              console.log('error: there seems to be some errors in the URL');
              return;
            }

            newUrl = sanitizeUrl(newUrl);

            // If there is a new valid URL
            if ($('iframe').attr('src') !== newUrl) {
              $('iframe').attr('src', newUrl);
            }

            // Watch for changes
            setTimeout(remotePreview, 1100);
          },

          error: function (jqXHR, textStatus, errorThrown) {
            /*jslint unparam: true */
            setTimeout(remotePreview, 2000);
            console.log('error: ' + textStatus + ', ' + errorThrown);
          }

        });
      }

      $(remotePreview);
    </script>
  </head>
  <body>
    <iframe src="http://h4kyJlNpMcZtxgaXlu1ifC.com" frameborder="0" scrolling="yes" marginheight="0" marginwidth="0"></iframe>
  </body>
</html>
